package com.atguigu.gmall.payment.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.atguigu.gmall.common.exception.OrderException;
import com.atguigu.gmall.oms.entity.OrderEntity;
import com.atguigu.gmall.payment.config.AlipayTemplate;
import com.atguigu.gmall.payment.interceptors.LoginInterceptor;
import com.atguigu.gmall.payment.pojo.PayAsyncVo;
import com.atguigu.gmall.payment.pojo.PayVo;
import com.atguigu.gmall.payment.pojo.PaymentInfoEntity;
import com.atguigu.gmall.payment.pojo.UserInfo;
import com.atguigu.gmall.payment.service.PaymentService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.signature.qual.IdentifierOrArray;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.Date;

@Controller
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private AlipayTemplate alipayTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("pay.html")
    public String paySelect(@RequestParam("orderToken")String orderToken, Model model){

        // 根据订单编号查询订单
        OrderEntity orderEntity = this.paymentService.queryOrderByToken(orderToken);

        // 1.订单是否为空
        if (orderEntity == null) {
            throw new OrderException("此订单不存在！");
        }

        // 2.订单是否属于当前用户
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        Long userId = userInfo.getUserId();
        if (orderEntity.getUserId() != userId){
            throw new OrderException("此订单不属于你！");
        }

        // 3.订单是否处于待付款
        if (orderEntity.getStatus() != 0) {
            throw new OrderException("此订单不可支付！");
        }

        model.addAttribute("orderEntity", orderEntity);

        return "pay";
    }

    @GetMapping("alipay.html")
    @ResponseBody // 以其他视图形式展示方法的返回结果集
    public Object alipay(@RequestParam("orderToken")String orderToken){
        // 根据订单编号查询订单
        OrderEntity orderEntity = this.paymentService.queryOrderByToken(orderToken);

        // 1.订单是否为空
        if (orderEntity == null) {
            throw new OrderException("此订单不存在！");
        }

        // 2.订单是否属于当前用户
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        Long userId = userInfo.getUserId();
        if (orderEntity.getUserId() != userId){
            throw new OrderException("此订单不属于你！");
        }

        // 3.订单是否处于待付款
        if (orderEntity.getStatus() != 0) {
            throw new OrderException("此订单不可支付！");
        }

        try {
            // 调用支付宝的远程接口打开支付页面
            PayVo payVo = new PayVo();
            payVo.setOut_trade_no(orderToken);
            // 注意！注意！注意！一定要写0.01
            payVo.setTotal_amount("0.01");
            payVo.setSubject("谷粒商城支付平台");
            // 记录支付对账
            Long payId = this.paymentService.savePaymentInfo(payVo);
            payVo.setPassback_params(payId.toString());
            return this.alipayTemplate.pay(payVo);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        throw new OrderException("跳转支付页面失败，请重试！");
    }

    @GetMapping("pay/success")
    public String paySuccess(){

        return "paysuccess";
    }

    @PostMapping("pay/ok")
    @ResponseBody
    public String payOk(PayAsyncVo asyncVo){

        // 1.验签：确保该回调是由支付宝发送的
        Boolean flag = this.alipayTemplate.checkSignature(asyncVo);
        if (!flag){
            return "failure";
        }

        // 2.校验业务参数：app_id out_trade_no total_amount
        String app_id = asyncVo.getApp_id();
        String out_trade_no = asyncVo.getOut_trade_no();
        String total_amount = asyncVo.getTotal_amount();
        String payId = asyncVo.getPassback_params();
        // 根据对账记录id查询对账记录
        PaymentInfoEntity paymentInfoEntity = this.paymentService.queryPaymentInfoById(payId);
        if (paymentInfoEntity == null || !StringUtils.equals(app_id, this.alipayTemplate.getApp_id())
                || !StringUtils.equals(out_trade_no, paymentInfoEntity.getOutTradeNo())
                || new BigDecimal(total_amount).compareTo(paymentInfoEntity.getTotalAmount()) != 0){
            return "failure";
        }

        // 3.判断支付状态trade_status：TRADE_SUCCESS
        if (!"TRADE_SUCCESS".equals(asyncVo.getTrade_status())){
            return "failure";
        }

        // 4.修改对账记录：更新为已支付
        paymentInfoEntity.setTradeNo(asyncVo.getTrade_no());
        paymentInfoEntity.setPaymentStatus(1);
        paymentInfoEntity.setCallbackTime(new Date());
        paymentInfoEntity.setCallbackContent(JSON.toJSONString(asyncVo));
        if (this.paymentService.updatePaymentInfo(paymentInfoEntity) == 1) {
            // 5.发送消息给OMS更新订单状态（oms->wms发送消息减库存）
            this.rabbitTemplate.convertAndSend("ORDER.EXCHANGE", "order.pay", out_trade_no);
        }

        // 6.返回success
        return "success";
    }
}
